import { ref, onMounted, computed, watch } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getQuestionDetailList } from '../api/quesdetails';
import { getQuestionList } from '../api/question';
import { getChoiceList } from '../api/choice';
import { insertAnswerResult, getAnswerResultList} from '../api/answerResult';
import { updateChoiceSetting } from '../api/choiceSetting';

// 导入体质类型API
import { getConstitutionList } from '../api/constitution';
// 导入测试分数API
import { insertTestScore } from '../api/testscore';
// 导入角色API
import { getAllRoles } from '../api/role';

// 导入BSHF相关API
import { getBSHFList, updateBSHF } from '../api/bshf';

export function useTestLogic() {
  const router = useRouter();
  const route = useRoute();
  const showLoginDropdown = ref(false);
  const showLoginAlert = ref(false);
  const currentSlide = ref(0);
  const totalSlides = ref(10);
  const answeredQuestions = ref(0);

  // 体质类型映射，改为响应式对象 - 移到这里声明
  const constitutionNames = ref({});

  const showFeaturePrompt = ref(false);
  const currentFeature = ref('');
  const promptPosition = ref({ top: 0, left: 0 });
  const jumpToIndex = ref(1);

  const role = ref('');
  const version = ref('');
  const questions = ref([]);
  const loading = ref(false);
  const queslistId = ref(null);

  const userAnswers = ref([]);
  const unansweredQuestion = ref(null);

  // 计算问题进度
  const progressText = computed(() => {
    return `${answeredQuestions.value}/${totalSlides.value}`;
  });

  // 根据版本名称获取问卷ID
  const getQueslistIdByName = (versionName) => {
    switch(versionName) {
      case '简洁版':
        return 1;
      case '普通版':
        return 2;
      case '详细版':
        return 3;
      default:
        return 1; // 默认简洁版
    }
  };

  // 选项映射，改为响应式对象
  const options = ref({});
  // 选项分数字典
  const optionScores = ref({});

  // 加载问题数据
  const loadQuestions = async () => {
    try {
      loading.value = true;

      // 获取选项数据
      const choiceRes = await getChoiceList({});
      if (choiceRes?.code === 0 && choiceRes.data && choiceRes.data.length > 0) {
        // 构建选项内容和分数字典
        options.value = choiceRes.data.reduce((acc, cur) => {
          acc[cur.choiceNum] = cur.choiceContent;
          return acc;
        }, {});
        optionScores.value = choiceRes.data.reduce((acc, cur) => {
          acc[cur.choiceNum] = cur.score;
          return acc;
        }, {});
      } else {
        // 使用默认选项
        options.value = {
          'A': '没有',
          'B': '很少',
          'C': '有时',
          'D': '经常',
          'E': '总是'
        };
        // 默认分数（如需调整请按实际需求）
        optionScores.value = {
          'A': 1,
          'B': 2,
          'C': 3,
          'D': 4,
          'E': 5
        };
      }

      // 原有获取问题列表的逻辑
      queslistId.value = getQueslistIdByName(version.value);
      console.log('设置问卷ID:', queslistId.value);
      
      // 2. 获取问题明细列表
      const detailRes = await getQuestionDetailList({ 
        queslistId: queslistId.value 
      });
      
      if (detailRes?.code !== 0 || !detailRes.data) {
        throw new Error('获取问题明细失败');
      }
      
      // 3. 提取quesId字段（根据后端实体字段名）
      const quesIds = detailRes.data.map(item => item.quesId);
      
      // 4. 获取问题列表（根据QuestionController接口规范）
      const questionRes = await getQuestionList(quesIds); 
      
      if (questionRes?.code !== 0 || !questionRes.data) {
        throw new Error('获取问题详情失败');
      }

      // 5. 更新问题列表（字段映射根据QuestionEntity）
      questions.value = questionRes.data.map(item => ({
        id: item.id,
        content: item.quesContent, // 对应ques_content字段
        constitution: item.constitution,
        isreverse: item.isreverse
      }));

      // 更新题目总数
      totalSlides.value = questions.value.length;
      // 初始化用户答案数组
      userAnswers.value = Array(totalSlides.value).fill('');
      // 初始化已回答问题数量
      answeredQuestions.value = 0;

    } catch (error) {
      console.error('加载失败:', error);
      ElMessage.error(error.message);
      useDefaultQuestions();
    } finally {
      loading.value = false;
    }
  };

  // 使用默认问题（当API调用失败时）
  const useDefaultQuestions = () => {
    questions.value = [
      { id: 1, content: "您精力充沛吗？", constitution: 1, isreverse: 0 },
      { id: 12, content: "您容易感到疲乏吗？", constitution: 2, isreverse: 0 },
      { id: 23, content: "您手脚发凉吗？", constitution: 3, isreverse: 0 },
      { id: 34, content: "您感到手脚心发热吗？", constitution: 4, isreverse: 0 },
      { id: 45, content: "您感到胸闷或腹部胀满吗？", constitution: 5, isreverse: 0 },
      { id: 56, content: "您面部或鼻部有油腻感或者油亮发光吗？", constitution: 6, isreverse: 0 },
      { id: 67, content: "您的皮肤在轻碰后会出现青紫瘀斑吗？", constitution: 7, isreverse: 0 },
      { id: 78, content: "您感到闷闷不乐、情绪低沉吗？", constitution: 8, isreverse: 0 },
      { id: 89, content: "您容易过敏吗？", constitution: 9, isreverse: 0 },
      { id: 4, content: "您能适应外界自然和社会环境的变化吗？", constitution: 1, isreverse: 0 }
    ];
    
    // 更新总题目数
    totalSlides.value = questions.value.length;
    // 初始化用户答案数组
    userAnswers.value = Array(totalSlides.value).fill('');
  };

  // 跳转到指定题目
  const jumpToQuestion = () => {
    if (jumpToIndex.value >= 1 && jumpToIndex.value <= totalSlides.value) {
      currentSlide.value = jumpToIndex.value - 1;
    }
  };

  // 选项分值映射（根据是否反向题目调整分值）
  const getOptionScore = (option, isReverse) => {
    const scores = {
      'A': isReverse ? 5 : 1,
      'B': isReverse ? 4 : 2,
      'C': isReverse ? 3 : 3,
      'D': isReverse ? 2 : 4,
      'E': isReverse ? 1 : 5
    };
    return scores[option] || 0;
  };

  // 计算体质得分
  const calculateConstitutionScores = () => {
    // 初始化各体质得分 - 使用constitutionNames中的id
    const scores = {};
    
    // 使用constitutionNames中的id初始化得分
    for (const id in constitutionNames.value) {
      scores[id] = 0;
    }
    
    // 各体质问题计数
    const counts = {};
    for (const id in constitutionNames.value) {
      counts[id] = 0;
    }
    
    // 计算各体质得分
    questions.value.forEach((question, index) => {
      const answer = userAnswers.value[index];
      if (answer) {
        const constitutionId = question.constitution;
        const score = getOptionScore(answer, question.isreverse);
        
        // 确保constitutionId存在于scores中
        if (scores[constitutionId] !== undefined) {
          scores[constitutionId] += score;
          counts[constitutionId]++;
        }
      }
    });
    
    // 计算各体质得分并调整比例
    const adjustedScores = {};
    for (const id in scores) {
      // 直接将原始分数映射到0-100的范围
      // 计算方式：(原始总分 / 最大可能总分) * 100
      const maxPossibleScore = counts[id] * 5; // 每题最高5分
      
      if (maxPossibleScore > 0) {
        // 计算百分比得分
        adjustedScores[id] = (scores[id] / maxPossibleScore) * 100;
      } else {
        adjustedScores[id] = 0;
      }
      
      // 确保分数在0-100范围内
      adjustedScores[id] = Math.min(100, Math.max(0, adjustedScores[id]));
      
      // 保留两位小数
      adjustedScores[id] = parseFloat(adjustedScores[id].toFixed(2));
    }
    
    // 打印体质得分详情
    console.log('体质得分详情:', adjustedScores);
    
    return adjustedScores;
  };

  // 判断体质类型
  const determineConstitutionType = (scores) => {
    // 获取平和质得分
    const balancedScore = scores[1] || 0;
    
    // 根据图片中的评分标准判断体质类型
    if (balancedScore >= 0 && balancedScore < 25) {
      // 0-25分，则为平和质
      return constitutionNames.value[1] || "平和质";
    } 
    else if (balancedScore >= 25 && balancedScore < 50) {
      // 25-50分，则基本为平和质，但是有某种倾向体质
      // 找出得分最高的偏颇体质
      let maxScore = 0;
      let maxType = null;
      for (let i = 2; i <= 9; i++) {
        if (scores[i] > maxScore) {
          maxScore = scores[i];
          maxType = i;
        }
      }
      return `${constitutionNames.value[1]}-${constitutionNames.value[maxType] || '未知体质'}`;
    }
    else if (balancedScore >= 50 && balancedScore < 75) {
      // 50-75分，有该种体质的倾向，需要注意
      // 找出得分最高的偏颇体质
      let maxScore = 0;
      let maxType = null;
      for (let i = 2; i <= 9; i++) {
        if (scores[i] > maxScore) {
          maxScore = scores[i];
          maxType = i;
        }
      }
      return constitutionNames.value[maxType] || `未知体质(${maxType})`;
    }
    else if (balancedScore >= 75) {
      // 75-100分，则为该种体质
      // 找出得分最高的偏颇体质
      let maxScore = 0;
      let maxType = null;
      for (let i = 2; i <= 9; i++) {
        if (scores[i] > maxScore) {
          maxScore = scores[i];
          maxType = i;
        }
      }
      
      // 检查是否有第二高分的体质
      let secondMaxScore = 0;
      let secondMaxType = null;
      for (let i = 2; i <= 9; i++) {
        if (i !== maxType && scores[i] > secondMaxScore) {
          secondMaxScore = scores[i];
          secondMaxType = i;
        }
      }
      
      // 如果第二高分体质得分在50-75之间，则为混合体质
      if (secondMaxScore >= 50 && secondMaxScore < 75) {
        return `${constitutionNames.value[maxType]}-${constitutionNames.value[secondMaxType]}`;
      }
      
      return constitutionNames.value[maxType] || `未知体质(${maxType})`;
    }
    
    // 默认返回未知体质
    return "未能确定体质";
  };
  
  // 加载体质类型数据
  const loadConstitutionTypes = async () => {
    try {
      const res = await getConstitutionList({ del: 0 });
      if (res?.code === 0 && res.data && res.data.length > 0) {
        // 构建体质类型映射
        const typeMap = {};
        res.data.forEach(item => {
          typeMap[item.id] = item.name; // 
        });
        constitutionNames.value = typeMap;
      } else {
        // 使用默认体质类型
        useDefaultConstitutionTypes();
      }
    } catch (error) {
      console.error('加载体质类型失败:', error);
      useDefaultConstitutionTypes();
    }
  };

  // 使用默认体质类型
  const useDefaultConstitutionTypes = () => {
    constitutionNames.value = {
      1: "平和质",
      2: "气虚质",
      3: "阳虚质",
      4: "阴虚质",
      5: "痰湿质",
      6: "湿热质",
      7: "血瘀质",
      8: "气郁质",
      9: "特禀质"
    };
    console.log('使用默认体质类型:', constitutionNames.value);
  };

  // 自动切换到下一题
  const autoNextSlide = () => {
    if (currentSlide.value < totalSlides.value - 1) {
      currentSlide.value++;
    }
  };

  // 轮播图控制函数
  const nextSlide = () => {
    currentSlide.value = (currentSlide.value + 1) % totalSlides.value;
    // 更新已回答问题数
    if (answeredQuestions.value < currentSlide.value + 1) {
      answeredQuestions.value = currentSlide.value + 1;
    }
  };

  const prevSlide = () => {
    currentSlide.value = (currentSlide.value - 1 + totalSlides.value) % totalSlides.value;
  };

  // 重置当前问题的答案
  const resetCurrentQuestion = () => {
    userAnswers.value[currentSlide.value] = '';
    // 更新已回答问题数量
    updateAnsweredCount();
  };

  // 添加一个计算属性来动态计算已回答的问题数量
  const updateAnsweredCount = () => {
    // 计算非空答案的数量
    answeredQuestions.value = userAnswers.value.filter(answer => answer !== '').length;
  };

  // 选择答案
  const selectAnswer = async (option) => {
    userAnswers.value[currentSlide.value] = option;
    
    // 更新已回答问题数量
    updateAnsweredCount();
    
    try {
      // 获取当前问题ID和选项ID
      const quesId = questions.value[currentSlide.value].id;
      const optionToId = { A: 1, B: 2, C: 3, D: 4, E: 5 }; // 字母选项映射数字ID
      const choiceId = optionToId[option]; // 转换选项字母为数字ID
      
      // 调用更新接口
      await updateChoiceSetting({
        id: quesId,
        quesId: quesId,
        choiceId: choiceId  // 现在会传递数字ID
      });
      
      // 选择后自动进入下一题
      setTimeout(() => {
        autoNextSlide();
      }, 300);
      
    } catch (error) {
      console.error('保存选项失败:', error);
      ElMessage.error('选项保存失败，请重试');
    }
  };

  // 格式化日期时间
  function formatDateTime(date) {
    const pad = n => n < 10 ? '0' + n : n;
    return date.getFullYear() + '-' +
      pad(date.getMonth() + 1) + '-' +
      pad(date.getDate()) + ' ' +
      pad(date.getHours()) + ':' +
      pad(date.getMinutes()) + ':' +
      pad(date.getSeconds());
  }

  // 角色ID映射
  const roleIdMap = ref({});

  // 加载角色数据
  const loadRoles = async () => {
    try {
      const res = await getAllRoles();
      if (res?.code === 0 && res.data && res.data.length > 0) {
        // 构建角色名称到ID的映射
        const idMap = {};
        res.data.forEach(item => {
          idMap[item.rolename] = item.id;
        });
        roleIdMap.value = idMap;
        console.log('角色ID映射:', roleIdMap.value);
      }
    } catch (error) {
      console.error('加载角色数据失败:', error);
    }
  };

  // 提交答案
  const submitAnswer = async () => {
    // 检查是否所有问题都已回答
    const allAnswered = userAnswers.value.every(answer => answer !== '');
    
    if (!allAnswered) {
      // 找出第一个未回答的问题
      const index = userAnswers.value.findIndex(answer => answer === '');
      unansweredQuestion.value = index + 1;
      
      // 3秒后自动隐藏提示
      setTimeout(() => {
        unansweredQuestion.value = null;
      }, 3000);
      
      // 跳转到未回答的问题
      currentSlide.value = index;
      return;
    }
    
    // 如果用户未登录，显示登录提示
    if (!checkUserLogin()) {
      showLoginAlert.value = true;
      setTimeout(() => {
        showLoginAlert.value = false;
      }, 2000);
      return;
    }
    
    try {
      // 计算体质得分
      const scores = calculateConstitutionScores();
      
      // 判断体质类型
      const constitutionType = determineConstitutionType(scores);
      
      // 从localStorage获取userInfo对象
      const userInfoStr = localStorage.getItem('userInfo');
      let userId = null;
      
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          userId = userInfo.id;
        } catch (e) {
          console.error('解析userInfo失败:', e);
          throw new Error('获取用户信息失败');
        }
      } else {
        throw new Error('用户未登录');
      }
      
      // 获取角色ID
      let curetypeId = 1; // 默认成人
      if (roleIdMap.value[role.value]) {
        curetypeId = roleIdMap.value[role.value];
      } else {
        // 如果没有找到对应的角色ID，使用简单映射
        curetypeId = role.value === '成人' ? 1 : (role.value === '儿童' ? 2 : 3);
      }
      
      // 确保queslistId有值
      if (!queslistId.value) {
        queslistId.value = getQueslistIdByName(version.value);
        console.log('提交前重新设置问卷ID:', queslistId.value);
      }
      
      // 获取最新的答题结果列表，不添加任何过滤条件
      const resultListRes = await getAnswerResultList({});
      
      // 获取最新记录的ID，并加1作为新记录的ID
      let newId = 1; // 默认从1开始
      if (resultListRes?.code === 0 && resultListRes.data && resultListRes.data.length > 0) {
        // 获取最新一条记录的ID
        const latestId = resultListRes.data.length;
        // 转为数字并加1
        newId = latestId + 1;
        console.log('生成新的测试结果ID:', newId);
      }
      
      // 构建选择题答案映射
      const choiceMap = {};
      questions.value.forEach((question, index) => {
        const answer = userAnswers.value[index];
        if (answer) {
          // 将选项字母转换为ID
          const optionToId = { A: 1, B: 2, C: 3, D: 4, E: 5 };
          choiceMap[question.id] = optionToId[answer];
        }
      });
      
      // 构建answerlistResult字段
      const answerlistResult = {
        choice: choiceMap,
        constitutionType: constitutionType
      };
      
      // 准备提交数据
      const data = {
        id: newId,
        userinfoId: userId,
        queslistId: queslistId.value,
        curetypeId: curetypeId,
        answerlistResult: JSON.stringify(answerlistResult) // 将对象转为JSON字符串
      };
      
      console.log('提交数据:', data);
      
      // 提交答题结果
      const res = await insertAnswerResult(data);
      
      if (res?.code === 0 && res.data) {
        // 提交各体质得分
        const scorePromises = [];
        for (const constitutionId in scores) {
          const scoreData = {
            resultId: newId, // 使用新生成的ID
            constitutionId: constitutionId,
            score: scores[constitutionId]
          };
          scorePromises.push(insertTestScore(scoreData));
        }
        
        // 等待所有得分提交完成
        await Promise.all(scorePromises);
        
        // 如果是回访测试，更新BSHF记录
        if (isFollowupTest.value && doctorId.value) {
          await updateFollowupResult(newId);
        }
        
        // 跳转到结果页面
        router.push(`/result?id=${newId}`);
      } else {
        throw new Error(res?.msg || '提交失败');
      }
    } catch (error) {
      console.error('提交失败:', error);
      ElMessage.error(error.message || '提交失败，请重试');
    }
  };
  
  // 更新回访结果
  const updateFollowupResult = async (resultId) => {
    try {
      // 查询符合条件的BSHF记录
      // 从localStorage获取userInfo对象
      const userInfoStr = localStorage.getItem('userInfo');
      let userId = null;
      
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr);
          userId = userInfo.id;
        } catch (e) {
          console.error('解析userInfo失败:', e);
          return;
        }
      } else {
        console.error('用户未登录');
        return;
      }
      
      const quesnaireId = getQueslistIdByName(version.value);
      
      console.log('正在更新回访记录，参数:', {
        userinfoId: userId,
        doctorId: doctorId.value,
        quesnaireId: quesnaireId,
        status: '回访中'
      });
      
      const queryParams = {
        userinfoId: userId,
        doctorId: doctorId.value,
        quesnaireId: quesnaireId,
        status: '回访中',
        del: 0
      };
      
      const bshfRes = await getBSHFList(queryParams);
      
      if (bshfRes?.code === 0 && bshfRes.data && bshfRes.data.length > 0) {
        // 获取第一条记录
        const bshf = bshfRes.data[0];
        
        // 更新记录，设置resultId
        const updateData = {
          id: bshf.id,
          resultId: resultId,
          status: '已回访'
        };
        
        const updateRes = await updateBSHF(updateData);
        if (updateRes?.code === 0) {
          console.log('回访记录已更新，关联了新的测试结果:', resultId);
        } else {
          console.error('更新回访记录失败:', updateRes?.msg);
        }
      } else {
        console.warn('未找到符合条件的回访记录');
      }
    } catch (error) {
      console.error('更新回访记录失败:', error);
      // 这里不抛出错误，因为主要功能已经完成
    }
  };

  // 检查用户登录状态
  const checkUserLogin = () => {
    const user = localStorage.getItem('userInfo');
    return user !== null;
  };

  const closeFeaturePrompt = () => {
    showFeaturePrompt.value = false;
  };

  const goToLoginFromPrompt = () => {
    showFeaturePrompt.value = false;
    router.push('/login');
  };

  const goToHome = () => {
    router.push('/');
  };

  const goToLogin = () => {
    console.log('去登录');
    router.push('/login');
  };

  const restartTest = () => {
    router.push('/');
  };

  // 添加doctorId相关变量
  const doctorId = ref(null);
  const isFollowupTest = ref(false);

  onMounted(async () => {
    // 获取从Main页面传递的角色和版本信息
    role.value = route.query.role || '';
    version.value = route.query.version || '';
    console.log('测试页面接收到的参数:', role.value, version.value);
    
    // 从URL获取dId参数，并设置doctorId和isFollowupTest
    if (route.query.dId) {
      doctorId.value = route.query.dId;
      isFollowupTest.value = true;
      console.log('检测到回访测试，医生ID:', doctorId.value);
    }
    
    // 加载角色数据
    await loadRoles();
    
    // 加载体质类型数据
    await loadConstitutionTypes();
    
    // 加载问题数据
    await loadQuestions();
  });

  return {
    showLoginDropdown,
    showLoginAlert,
    currentSlide,
    totalSlides,
    answeredQuestions,
    showFeaturePrompt,
    currentFeature,
    promptPosition,
    jumpToIndex,
    role,
    version,
    questions,
    loading,
    queslistId,
    userAnswers,
    unansweredQuestion,
    progressText,
    options,
    optionScores,
    constitutionNames, // 添加到返回值中
    jumpToQuestion,
    nextSlide,
    prevSlide,
    resetCurrentQuestion,
    selectAnswer,
    submitAnswer,
    checkUserLogin,
    closeFeaturePrompt,
    goToLoginFromPrompt,
    goToHome,
    goToLogin,
    restartTest,
    doctorId,
    isFollowupTest,
    roleIdMap,
  };
}